<?php
/**
 * 评论
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-16
 * Time: 11:34
 */

namespace App\Http\Controllers\Api\V1\Front\Mall;


use App\Http\Controllers\Controller;
use App\Models\CommodityComment;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\OrderRefund;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class OrderCommentController extends Controller
{
    public function store(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data,[
            'orderNo'       =>'required',
            'commodityList' =>'required',
            'userId'  =>'required'
        ]);
        if($validator->fails()){
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $user = User::find($data['userId']);
        $commodityList = $data['commodityList'];
        $commodityComment = [];
        try{
            \DB::beginTransaction();
            foreach ($commodityList as $key=>$value){
                $commodityComment[$key]['content'] = $value['content'];
                $commodityComment[$key]['userId'] = $data['userId'];
                $commodityComment[$key]['nickName'] = $user['nickName'];
                $commodityComment[$key]['avatarUrl'] = $user['avatarUrl'];
                $commodityComment[$key]['orderNo'] = $data['orderNo'];
                $commodityComment[$key]['commodityId'] = $value['commodityId'];
            }

            $orderTotal = OrderDetail::where('orderNo',$data['orderNo'])->count();//计算购买的商品总数（只计算单个的）
            $orderRefund = OrderRefund::where('orderNo',$data['orderNo'])->count();
            $orderRefund1 = OrderRefund::where(['orderNo'=>$data['orderNo'],'refundStatus'=>'FAILED'])->count();
            $orderTotal = $orderTotal-$orderRefund+$orderRefund1;
            $commentTotal= count($commodityComment);
            if($orderTotal != $commentTotal){
                throw new \Exception("参数错误");
            }
            $status = Order::where(['orderNo'=>$data['orderNo'],'orderStatus'=>'WAITCOMMENT'])->update(['orderStatus'=>'ORDERFINISH','finishTime'=>date("Y-m-d H:i:s",time())]);
            if(!$status){
                throw new \Exception("更新订单失败");
            }
            $status = CommodityComment::insert($commodityComment);
            if(!$status){
                throw new \Exception("插入评论失败");
            }
            \DB::commit();
            return $this->apiResponse(true);
        }catch (\Exception $e){
            \DB::rollback();
            \Log::error("OrderCommentController store".$e->getMessage());
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }

    }
}